package p.ithorns.framework.mysql.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.handlers.StrictFill;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;

import org.apache.ibatis.reflection.MetaObject;
import p.ithorns.framework.core.context.UserContext;
import p.ithorns.framework.core.model.UserLoginInfo;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author ithorns
 */
// @Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private String getCurrentUserId() {
        return Optional.ofNullable(UserContext.get()).map(UserLoginInfo::getId).orElse("0");
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(metaObject.getOriginalObject().getClass());
        List<StrictFill<?, ?>> strictFills = new ArrayList<>();
        strictFills.add(new StrictFill<>("createTime", LocalDateTime.class, LocalDateTime::now));
        strictFills.add(new StrictFill<>("createBy", String.class, this::getCurrentUserId));
//                strictFills.add(new StrictFill<>("creatorCode", String.class, headers::getEmpCode));
//                strictFills.add(new StrictFill<>("orgCode", String.class, headers::getOrgCode));
        this.strictInsertFill(tableInfo, metaObject, strictFills);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(metaObject.getOriginalObject().getClass());
        List<StrictFill<?, ?>> strictFills = new ArrayList<>();
        strictFills.add(new StrictFill<>("updateTime", LocalDateTime.class, LocalDateTime::now));
        // 尝试写入当前用户ID
        strictFills.add(new StrictFill<>("updateBy", String.class, this::getCurrentUserId));

        this.strictUpdateFill(tableInfo, metaObject, strictFills);
    }
}
